package com.dubito.gallery.ui.settings

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.dubito.gallery.data.ColorThemeSettings
import com.dubito.gallery.data.DarkThemeSettings
import com.dubito.gallery.data.SettingsRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.koin.core.component.KoinComponent
import org.koin.core.component.get

sealed interface SettingsUiState {
    object Loading : SettingsUiState
    data class Success(
        val darkTheme: DarkThemeSettings,
        val colorTheme: ColorThemeSettings,
        val tapCountToOpenSettings: Int,
        val multiGoBack: Int
    ) : SettingsUiState
}

class SettingsViewModel : ViewModel(), KoinComponent {
    private val settingsRepository: SettingsRepository = get()

    val uiState: StateFlow<SettingsUiState> =
        settingsRepository.appSettingsFlow.map { appSettings ->
            SettingsUiState.Success(
                darkTheme = appSettings.darkTheme,
                colorTheme = appSettings.colorTheme,
                tapCountToOpenSettings = appSettings.tapCountToOpenSettings,
                multiGoBack = appSettings.multiGoBack
            )
        }.stateIn(
            scope = viewModelScope,
            started = SharingStarted.WhileSubscribed(5000),
            initialValue = SettingsUiState.Loading
        )

    fun setDarkTheme(darkTheme: DarkThemeSettings) {
        viewModelScope.launch {
            settingsRepository.setDarkTheme(darkTheme = darkTheme)
        }
    }

    fun setColorTheme(colorTheme: ColorThemeSettings) {
        viewModelScope.launch {
            settingsRepository.setColorTheme(colorTheme = colorTheme)
        }
    }

    fun setTapCountOpenSettings(tapCount: Int) {
        viewModelScope.launch {
            settingsRepository.setTapCountOpenSettings(tapCountToOpenSettings = tapCount)
        }
    }

    fun setMultiGoBack(multiGoBack: Int) {
        viewModelScope.launch {
            settingsRepository.setMultiGoBack(multiGoBack = multiGoBack)
        }
    }
}